//
//  ProvinceUniversityViewController.m
//  DIsciplineSelectPartner
//
//  Created by 唐秦崴 on 15/3/14.
//  Copyright (c) 2015年 Lizzy. All rights reserved.
//

#import "ProvinceUniversityViewController.h"
#import "UniversityDetailViewController.h"
#import "Unit.h"
#import "University.h"
#import <BmobSDK/Bmob.h>

@interface ProvinceUniversityViewController ()

@property (nonatomic,strong) NSMutableArray* unitsArray; // 临时在本页面存放招生单元的数组
@property (nonatomic,strong) University* university;     // 临时在本页面存放university

@end


static const int BMOBQUERY_LIMIT = 1000;  // Bmob 单次查询数据数目的上限

@implementation ProvinceUniversityViewController


// 重写getter，防止addObject的时候该属性为nil
-( NSMutableArray* ) unitsArray
{
    if (!_unitsArray) { _unitsArray = [[ NSMutableArray alloc ] init ]; };
    return _unitsArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置返回按钮的颜色
    self.navigationController.navigationBar.tintColor = [ UIColor whiteColor ];
    // 设置返回按钮文字
    // Set this in every view controller so that the back button displays back instead of the root view controller name
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    // 设置title
    self.navigationItem.title = [[self.universitysArray objectAtIndex:0 ] province];
    
    // 设置分割线样式
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = [UIColor colorWithRed:236/255.0 green:208/255.0 blue:191/255.0 alpha:1 ];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    // Return the number of sections.
//    return 1;
//}

// tableView每个分区的行数，可以为各个分区设置不同的行数，根据section的值判断即可
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [ self.universitysArray count ];
}

// 实现每一行Cell的内容，tableView重用机制
static const float CELL_ARROW_X       = 280;
static const float CELL_ARROW_Y       = 10;
static const float CELL_ARROW_HEIGHT  = 20;
static const float CELL_ARROW_WIDTH   = 20;
-(UITableViewCell* ) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"cellIdentifier";
    
    UITableViewCell* cell = [ tableView dequeueReusableCellWithIdentifier:cellIdentifier ];
    
    if ( nil == cell ) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    University* university  = [ self.universitysArray objectAtIndex:indexPath.row ];
    cell.textLabel.text     = university.name;
    
    // 设置右侧小箭头
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"arrow_right_orange"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake( CELL_ARROW_X , CELL_ARROW_Y, CELL_ARROW_WIDTH, CELL_ARROW_HEIGHT)];
    [cell.contentView addSubview:button];
    
    return cell;
}

// 设置选中某行的处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( 0 == indexPath.section )
    {
        self.university = [self.universitysArray objectAtIndex:indexPath.row];
        
        // 清空数组
        [ self.unitsArray removeAllObjects ];
        
        // 通过unit表中的university字段查招生单元（该方法暂不使用）
//        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Unit"];
//        bquery.limit = BMOBQUERY_LIMIT;
//        [bquery whereKey:@"university" equalTo: self.university.name ];
        
        // Bmob查询, 查询招生单元的数组
        // 通过relatedTo 查询关联来查
        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Unit"];
        bquery.limit = BMOBQUERY_LIMIT;
        BmobObject *universityObj = [BmobObject objectWithoutDatatWithClassName:@"University" objectId:self.university.objectId ];
        [bquery whereObjectKey:@"unit" relatedTo:universityObj];
        [bquery orderByAscending:@"createdAt"];
        [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            
            for (BmobObject *obj in array) {
                Unit* unit = [[ Unit alloc ] initWithBmobObject:obj];
                [ self.unitsArray addObject:unit ];
            }
            // 跳转页面
            [ self performSegueWithIdentifier:@"listToUniversityDetail" sender:self.university ];

        }];
        
    }else
    {
        NSLog( @"You chosed section unknown " );
    }
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ( [segue.destinationViewController isKindOfClass:[ UniversityDetailViewController class]] ) {
        if ([segue.identifier isEqualToString:@"listToUniversityDetail"]) {
           
            UniversityDetailViewController* udVC = (UniversityDetailViewController*) segue.destinationViewController;
            udVC.university = [[ University alloc ] initWithUniversity:sender ];
            udVC.unitsArray = self.unitsArray;
            
        }
    }
}

@end
